/**
 * @Author: panda
 * @Date: 2022-05-18 11:00
 * @Description: 腾讯云cos
 */
import {
  CosError,
  CosSdkError,
  DeleteObjectResult,
  GetAuthorizationCallbackParams,
  GetAuthorizationOptions,
  ProgressInfo,
  UploadFileResult,
} from "cos-js-sdk-v5";
import {cosApi} from '@/api/cos'
import {v4 as uuidv4} from 'uuid'
import {UploadRequestOptions} from "element-plus/es/components/upload/src/upload";
import {UploadProgressEvent} from "element-plus/lib/components";
import {ElMessage, ElMessageBox} from "element-plus/es";
import {useUserStore} from "@/store/modules/user";

const COS = require('cos-js-sdk-v5')
const bucket = 'panda-1308597681'
const region = 'ap-guangzhou'
const userStore = useUserStore();

// 创建cos对象，并获取临时密钥
export const cos = new COS({
  // getAuthorization 必选参数
  getAuthorization: function (options: GetAuthorizationOptions, callback: (params: GetAuthorizationCallbackParams) => void) {
    cosApi.getCredential({}).then(res => {
      console.log(res)
      if (res.data.code !== 200) {
        ElMessageBox.alert(res.data.msg, '错误提示', {
          confirmButtonText: '好的',
        },).then(r => console.log(r))
        return
      } else {
        const {data} = res.data
        console.log(res)
        const credentials = data.credentials
        callback({
          TmpSecretId: credentials.tmpSecretId,
          TmpSecretKey: credentials.tmpSecretKey,
          SecurityToken: credentials.sessionToken,
          StartTime: data.startTime,
          ExpiredTime: data.expiredTime
        })
      }
    }).catch(callback)
  }
})

// 文件更名，格式：时间戳-uuid+文件格式 copy
function formatFilename(file: File, callback: Function) {
  const time = new Date().getTime();
  const uuid = uuidv4()
  const results = /\.\w+$/.exec(file.name)
  const extname = results ? results[0] : ''
  const fileReader = new FileReader()
  fileReader.readAsBinaryString(file)
  callback('time-' + time + '-' + uuid + extname)
}

// 上传方法 copy
export function upload(uploadFile: UploadRequestOptions) {

  return new Promise((resolve, reject) => {

    formatFilename(uploadFile.file, (filename: string) => {
      const imgType = ["gif", "jpeg", "jpg", "bmp", "png"];
      const videoType = ["avi", "wmv", "mkv", "mp4", "mov", "rm", "3gp", "flv", "mpg", "rmvb"];
      let dir = ''
      if (RegExp("\.(" + imgType.join("|") + ")$", "i").test(filename.toLowerCase())) {
        dir = 'image/';
      } else if (RegExp("\.(" + videoType.join("|") + ")$", "i").test(filename.toLowerCase())) {
        dir = 'video/';
      }
      if (uploadFile.file.size / (1024 * 1024) < 50) {
        cos.uploadFile({
          Bucket: bucket,
          Region: region,
          Key: dir + 'userId-' + userStore.getUserInfo.id + '-' + filename,
          StorageClass: 'STANDARD',
          Body: uploadFile.file,
          onProgress: (evt: ProgressInfo) => {
            uploadFile.onProgress({
              percent: evt.percent * 100
            } as UploadProgressEvent)
          },
        }, (err: CosSdkError, data: UploadFileResult) => {
          if (err) {
            console.log(err)
            reject(err)
          } else {
            resolve('https://' + data.Location)
          }
        })
      } else {
        cos.sliceUploadFile({
          Bucket: bucket,
          Region: region,
          Key: dir + 'userId-' + userStore.getUserInfo.id + '-' + filename,
          StorageClass: 'STANDARD',
          Body: uploadFile.file,
          onProgress: (evt: ProgressInfo) => {
            uploadFile.onProgress({
              percent: evt.percent * 100
            } as UploadProgressEvent)
          },
        }, (err: CosSdkError, data: UploadFileResult) => {
          if (err) {
            console.log(err)

            reject(err)
          } else {
            resolve('https://' + data.Location)
          }
        })
      }
    })
  })
}

//上传封面
export function uploadCover(file: Blob) {
  return new Promise((resolve, reject) => {

    const type = file.type.split('/');
    formatFilename(file as File, (filename: string) => {
      cos.uploadFile({
        Bucket: bucket,
        Region: region,
        Key: 'image/' + 'userId-' + userStore.getUserInfo.id + '-' + filename + '.' + type[1],
        StorageClass: 'STANDARD',
        Body: file,
      }, (err: CosSdkError, data: UploadFileResult) => {
        if (err) {
          console.log(err)
          reject(err)
        } else {
          resolve('https://' + data.Location)
        }
      })
    })
  })
}


export function deleteObject(key: string) {
  cos.deleteObject({
    Bucket: bucket, /* 填入您自己的存储桶，必须字段 */
    Region: region,  /* 存储桶所在地域，例如ap-beijing，必须字段 */
    Key: key,  /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
  }, function (err: CosError, data: DeleteObjectResult) {
    if (err) {
      console.log(err)
    } else {
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      console.log(data)
    }
  })
}

export default cos
